﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebUI.Controls;
using POSSystem.BLL;

namespace WebUI.EditPages
{
    public partial class SalePopup : BasePage
    {
        int orderID;

        protected void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);

            saleLookup.OnAddIMEI = saleLookup_OnAddIMEI;
            saleLookup.OnAddProduct = saleLookup_OnAddProduct;
            sales.OnFinishSubmit = OnSubmitted;
            gridSelectedItems.OnNeedDataSource = gridSelectedItems_OnNeedDataSource;

            if(!string.IsNullOrEmpty(Request.QueryString[ID]))
                orderID = int.Parse(Request.QueryString[ID]);

            if (!IsPostBack)
            {
                gridSelectedItems.Refresh();
                gridSelectedItems.Columns[0].Visible = false;
                gridSelectedItems.Columns[4].Visible = false;
                gridSelectedItems.Columns[5].Visible = false;
                gridSelectedItems.Columns[6].Visible = false;
                gridSelectedItems.ReadOnly = true;

                sales.NewInvoice();

                if(Order.s_VoucherID != "")
                {
                    Vouchers vc = new Vouchers();
                    vc.LoadByPrimaryKey(Order.VoucherID);
                    if (vc.RowCount > 0)
                        sales.VoucherCode = vc.Code;
                }

                for (int i = 0; i < Items.RowCount; i++)
                {
                    if (Items.Category == OrderItemCategory.Product)
                        sales.AddProduct(Items.ProductID, Items.Quantity);
                    else if (Items.Category == OrderItemCategory.BusinessCard)
                        sales.AddBusinessCard(Items.ProductID, Items.s_ProductName, Items.Quantity, Items.CustomerPrice, Items.GST);
                    Items.MoveNext();
                }

                int statusID = POSSystem.BLL.CustomerOrders.GetStatus(orderID);
                if (OrderStatus.InvoiceCreated == statusID || statusID == OrderStatus.Shipped )
                {
                    ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), string.Format("alert('The invoice for this order has been created!');window.returnValue=1;window.close();"), true);
                    return;
                }
            }

            ScriptManager.RegisterClientScriptInclude(this, typeof(Page), Guid.NewGuid().ToString(), ResolveUrl("~/Script/prototype.js"));
            ScriptManager.RegisterClientScriptInclude(this, typeof(Page), Guid.NewGuid().ToString(), ResolveUrl("~/Script/scriptaculous.js?load=effects"));
            ScriptManager.RegisterClientScriptInclude(this, typeof(Page), Guid.NewGuid().ToString(), ResolveUrl("~/Script/lightbox.js"));
        }

        protected void OnSubmitted(object sender, FinishSubmitArg e)
        {
            POSSystem.BLL.CustomerOrders order = new POSSystem.BLL.CustomerOrders();
            order.LoadByPrimaryKey(orderID);

            order.StatusID = OrderStatus.InvoiceCreated;
            order.s_ShipDate = "";
            order.InvoiceID = e.InvoiceID;
            order.Save();

            ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), string.Format("window.returnValue={0};", 1), true);
        }

        View_OrderItems items;

        public View_OrderItems Items
        {
            get { 
                if (items == null)
                    items = View_OrderItems.GetOrderItems(orderID);
                return items;
            }
            set { items = value; }
        }

        POSSystem.BLL.CustomerOrders order;
        public POSSystem.BLL.CustomerOrders Order
        {
            get
            {
                if (order == null)
                    order = POSSystem.BLL.CustomerOrders.GetOrdersById(orderID);
                return order;
            }
            set { order = value; }
        }

        protected void gridSelectedItems_OnNeedDataSource(Object sender, EventArgs e)
        {
            gridSelectedItems.DataSource = Items.DefaultView;
            ScriptManager.RegisterStartupScript(this, typeof(Page), Guid.NewGuid().ToString(), "initLightbox();", true); 
        }

        public void saleLookup_OnAddIMEI(object sender, ListItemEventArgs e)
        {
            try
            {
                string imei = e.Data["IMEI"].ToString();
                sales.AddIMEI(imei);
            }
            catch (Exception ex)
            {
                ErrorLog.WriteToFile("Sales.aspx.cs", "saleLookup_OnAddIMEI", ex.StackTrace);
                ShowErrorMessage(panelErr, "(*) Error in add IMEI: " + ex.Message);
                updateErr.Update();
            }
        }

        public void saleLookup_OnAddProduct(object sender, ListItemEventArgs e)
        {
            try
            {
                int productID = (int)e.Data["ProductID"];
                int quantity = (int)e.Data["Quantity"];
                sales.AddProduct(productID, quantity);
            }
            catch (Exception ex)
            {
                ErrorLog.WriteToFile("Sales.aspx.cs", "saleLookup_OnAddProduct", ex.StackTrace);
                ShowErrorMessage(panelErr, "(*) Error in add product: " + ex.Message);
                updateErr.Update();
            }
        }
    }
}